package com.shiro.demo.utils;

import org.apache.commons.lang3.StringUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

public class MD5Util {

    public static void main(String[] args) {
        //字符串加密
        String str = "123456";
        String salt = getSalt();
        System.out.println(salt);
        System.out.println(getMD5CodeBySalt(str,salt));
    }

    //对字符串进行MD5编码
    public static String getMD5Code(String str){
        if(StringUtils.isBlank(str)){
            return null;
        }
        try {
            //创建具有指定算法名称的信息摘要
            MessageDigest md = MessageDigest.getInstance("MD5");
            //使用指定的字节数组对摘要进行最后的更新，然后完成摘要计算
            byte[] results = md.digest(str.getBytes());
            //将得到的字节数组编程字符串返回
            String resultString = byteArrayToHexString(results);
            return resultString.toUpperCase();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return null;
    }

    //对字符串进行MD5编码加盐操作
    public static String getMD5CodeBySalt(String str,String salt){
        if(StringUtils.isBlank(str)){
            return null;
        }
        return getMD5Code(getMD5Code(str)+salt);
    }

    //转换字节数组为十六进制字符串
    private static String byteArrayToHexString(byte[] results){
        StringBuffer resultNew = new StringBuffer();
        for(int i = 0;i < results.length;i++){
            resultNew.append(byteToHexString(results[i]));
        }
        return resultNew.toString();
    }


    //16进制下数字到字符的映射数组
    private static String[] HEXDIGITS = new String[]{"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"};
    //将字节转化成十六进制的字符串
    private static String byteToHexString(byte b){
        int byteNum = b;
        if(byteNum < 0){
            byteNum = byteNum + 256;
        }
        int d1 = byteNum / 16;
        int d2 = byteNum % 16;
        return HEXDIGITS[d1]+HEXDIGITS[d2];
    }
    //传入的字符串加密后和Md5字符串的比较，常用语登录时密码的核对
    private static boolean compareStringWithMD5Code(String str,String MD5Code){
        boolean isEquals = false;
        if(StringUtils.isBlank(str)){
            return isEquals;
        }
        if(MD5Code.equals(getMD5Code(str))){
            isEquals = true;
        }
        return isEquals;
    }

    //生成一个10位的随机salt
    public static String getSalt(){
        String salt = "";
        Random rand = new Random();
        for(int i=0;i<10;i++){
            int num = rand.nextInt(3);
            switch(num){
                case 0:
                    char c1 = (char)(rand.nextInt(26)+'a');//生成随机小写字母
                    salt += c1;
                    break;
                case 1:
                    char c2 = (char)(rand.nextInt(26)+'A');//生成随机大写字母
                    salt += c2;
                    break;
                case 2:
                    salt += rand.nextInt(10);//生成随机数字
            }
        }
        return salt;
    }
}
